package com.chajia.util;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBHelper {

	/***
	 * 读
	 * @param tag
	 * @param sql
	 * @param vals
	 * @return
	 * @throws SQLException
	 */
	public static ResultSet read(String tag,String sql,String[] vals) throws SQLException{
		ConnectionProxy cont=Transaction.getConnection(tag);
		if(cont==null)return null;
		return cont.sql_query(sql, vals);
	}

    /**
     * 读 可变参数不限类型
     * @param tag
     * @param sql
     * @param p
     * @return
     * @throws SQLException
     */
    public static ResultSet readO(String tag,String sql, Object... p) throws SQLException{
        ConnectionProxy cont=Transaction.getConnection(tag);
        if(cont==null)return null;
        return cont.sql_query(sql, p);
    }
	/***
	 * 写
	 * @param tag
	 * @param sql
	 * @param vals
	 * @return
	 * @throws SQLException
	 */
	public static int write(String tag,String sql,String[] vals) throws SQLException{
		ConnectionProxy cont=Transaction.getConnection(tag);
		if(cont==null)return -1;
		return cont.sql_update(sql, vals);
	}
    public static int writeO(String tag,String sql, Object... p)throws SQLException {
        ConnectionProxy cont=Transaction.getConnection(tag);
        if(cont==null)return -1;
        return cont.sql_update(sql, p);
    }
	/***
	 * 创建批处理对象
	 * @param tag
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static PreparedStatement prepare(String tag,String sql)throws SQLException{
		ConnectionProxy cont=Transaction.getConnection(tag);
		return cont.prepareStatement(sql);
	}
	/***
	 * 创建一个表
	 * @param tag
	 * @param table
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static boolean create(String tag,String table,String sql) throws SQLException{
		ResultSet rs = read(tag, "show tables like '"+table+"';", null);
		if(rs.next())return true;
		return write(tag,sql,null)==0;
	}
}
